/**
 * 从文件路径中提取文件名
 * 如 E:\test\test2 结果为test2
 * E:\ 结果为E:
 * E:test 结果为test 如果是盘符下第一级目录会这样返回
 * */
function extractFilename(filePath) {
  let lastSepIndex = filePath.lastIndexOf(PATH_SEP);
  let diskSymIndex = filePath.lastIndexOf(':');
  if (lastSepIndex == filePath.length - 1) {
    return filePath.substring(0, lastSepIndex);
  } else if (lastSepIndex == -1) {
    return filePath.substring(diskSymIndex + 1);
  }
  return filePath.substring(lastSepIndex + 1);
}

/**
 * 分离文件名和拓展名以长度为2数组返回，0为文件名，1为拓展名
 * 如果没有拓展名，1为null
 */
function splitFilenameExtension(filename) {
  let dotIndex = filename.lastIndexOf('.');
  return dotIndex != -1 ? [filename.substring(0, dotIndex), filename.substring(dotIndex)] : [filename, null];
}

/**
 * 根据给的参数计算页码范围
 * */
function calPageWindow(windowSize, currentPage, pageSize, total) {
  let totalPage = Math.ceil(total / pageSize);

  let start = currentPage - Math.floor(windowSize / 2);
  let end = (windowSize & 1) == 1 ? currentPage + Math.floor(windowSize / 2) : currentPage + Math.floor(windowSize / 2) - 1;
  if (end > totalPage) {
      start = Math.max(1, start - (end - totalPage));
      end = totalPage;
  } else if (start < 1) {
      end = Math.min(totalPage, end + (1 - start));
      start = 1;
  }
  return [start, end];
}

function calPage(windowSize, currentPage, pageSize, total) {
  let pageBetween = calPageWindow(windowSize, currentPage, pageSize, total)
  let pages = [];
  for (let i = pageBetween[0]; i <= pageBetween[1]; i++) {
    pages.push(i);
  }
  return pages;
}

function shallowCopyObj(obj) {
  return Object.assign({}, obj);
}

function toQueryParamStr(obj) {
 var str = [];
 for (var p in obj)
  if (obj.hasOwnProperty(p)) {
   str.push(encodeURIComponent(p) + "=" + obj[p]);
  }
 return str.join("&");
}

export default {
  extractFilename,
  splitFilenameExtension,
  calPage,
  shallowCopyObj,
  toQueryParamStr,
}
